//  UsrFileViewController.m
//  muscleLife
//
//  Created by xalo on 16/4/29.
//  Copyright © 2016年 HeavenAndHell. All rights reserved.
//

#import "UsrFileViewController.h"



@interface UsrFileViewController ()<UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *usrImg;
@property (weak, nonatomic) IBOutlet UITextField *uname;
@property (weak, nonatomic) IBOutlet UITextField *genderText;
@property (weak, nonatomic) IBOutlet UITextField *brithDayText;
@property (weak, nonatomic) IBOutlet UITextField *cityText;
@property (weak, nonatomic) IBOutlet UITextField *heightText;
@property (weak, nonatomic) IBOutlet UITextField *weightText;
@property (weak, nonatomic) IBOutlet UITextField *BMIText;
@property (weak, nonatomic) IBOutlet UITextView *introduceText;

@property(nonatomic, retain)AVUser* currentUsr;

@end

@implementation UsrFileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.currentUsr = [AVUser currentUser];
    [self displayInterfaceSetting];
    [self setHeadPortrait];
    NSLog(@"weidth--%f,---%f",self.usrImg.frame.size.width,self.usrImg.frame.size.height);

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.usrImg layoutIfNeeded];
    [[self.usrImg layer] setCornerRadius:self.usrImg.frame.size.height/2.0];
    [[self.usrImg layer] setMasksToBounds:YES];

    NSLog(@"weidth--%f,---%f",self.usrImg.frame.size.width,self.usrImg.frame.size.height);
}

-(void)setHeadPortrait{

//    self.usrImg.userInteractionEnabled = YES;
    UITapGestureRecognizer* singTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(alertHeadPortrait:)];
    [self.usrImg addGestureRecognizer:singTap];
}

-(void)alertHeadPortrait:(UITapGestureRecognizer*)gesture{
    /**
     *  弹出提示框
     */
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    //按钮：从相册选择，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        //初始化UIImagePickerController
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
        //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
        //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
        PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //允许编辑，即放大裁剪
        PickerImage.allowsEditing = YES;
        //自代理
        PickerImage.delegate = self;
        //页面跳转
        [self presentViewController:PickerImage animated:YES completion:nil];
    }]];

    //按钮：拍照，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        /**
         其实和从相册选择一样，只是获取方式不同，前面是通过相册，而现在，我们要通过相机的方式
         */
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式:通过相机
        PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
        PickerImage.allowsEditing = YES;
        PickerImage.delegate = self;
        [self presentViewController:PickerImage animated:YES completion:nil];
    }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];


}
//PickerImage完成后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeHeadImg" object:nil userInfo:@{@"img":newPhoto}];
    self.usrImg.image = newPhoto;
    //将图片存储起来
    AVFile* oldFile = [self.currentUsr objectForKey:UIMGKEY];
    if (oldFile) {
        [oldFile deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            NSLog(@"success:%d",succeeded);
            NSData* data = UIImageJPEGRepresentation(newPhoto, 1.0);
            AVFile* file = [AVFile fileWithName:[AVUser currentUser].username data:data];
            [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                NSLog(@"%@",file.url);
                [self setUsrInfoWithkey:UIMGKEY object:file];
            }];
        }];
    }else{
        NSData* data = UIImageJPEGRepresentation(newPhoto, 1.0);
        AVFile* file = [AVFile fileWithName:[AVUser currentUser].username data:data];
        [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            NSLog(@"%@",file.url);
            [self setUsrInfoWithkey:UIMGKEY object:file];
        }];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}


//用户名
- (IBAction)unameSave:(UITextField *)sender {

    [self setUsrInfoWithkey:UNAMEKEY object:sender.text];
}
//性别
- (IBAction)genderSave:(UITextField *)sender {

    [self setUsrInfoWithkey:UGENDERKEY object:sender.text];
}
//生日
- (IBAction)brithdaySave:(UITextField *)sender {

    [self setUsrInfoWithkey:UBRITHDAYKEY object:sender.text];
}
//城市
- (IBAction)citySave:(UITextField *)sender {

    [self setUsrInfoWithkey:UCITYKEY object:sender.text];
}

//体重
- (IBAction)weightSave:(UITextField *)sender {
    NSNumber* weightNumber = [self numberWithString:sender.text];
    [self setUsrInfoWithkey:UWEIGHTKEY object:weightNumber];

}

//身高
- (IBAction)heightSave:(UITextField *)sender {
    NSNumber* heightNumber = [self numberWithString:sender.text];
    [self setUsrInfoWithkey:UHEIGHTKEY object:heightNumber];
}


//string转nsnumber,float型
-(NSNumber*)numberWithString:(NSString*)string{

    NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
    id result = [formatter numberFromString:string];
    if (!(result)) {
        result = string;
    }
    float number = [result floatValue];
    return [NSNumber numberWithFloat:number];
}

//显示前先读取当前用户的信息
-(void)displayInterfaceSetting{

    self.uname.text = [self.currentUsr objectForKey:UNAMEKEY];
    self.genderText.text = [self.currentUsr objectForKey:UGENDERKEY];
    self.brithDayText.text = [self.currentUsr objectForKey:UBRITHDAYKEY];
    self.cityText.text = [self.currentUsr objectForKey:UCITYKEY];
    float height = [[self.currentUsr objectForKey:UHEIGHTKEY] floatValue];
    float weight = [[self.currentUsr objectForKey:UWEIGHTKEY] floatValue];
    self.heightText.text = [[self.currentUsr objectForKey:UHEIGHTKEY] stringValue];
    self.weightText.text = [[self.currentUsr objectForKey:UWEIGHTKEY] stringValue];
    self.introduceText.text = [self.currentUsr objectForKey:UINTRODUCEKEY];
    AVFile* file = [self.currentUsr objectForKey:UIMGKEY];
    if (file) {
//        NSLog(@"%@",file.url);
        [self.usrImg sd_setImageWithURL:[NSURL URLWithString:file.url] placeholderImage:nil];
    }else{
        self.usrImg.image = [UIImage imageNamed:kHeadImagePlaceholderFileName];//占位图
    }
#warning 警告BMI的计算
    //BMI值得计算
    self.BMIText.userInteractionEnabled = NO;
    float BMI = weight / (height/100.0)*(height/100.0);
    self.BMIText.text = [[NSNumber numberWithFloat:BMI] stringValue];
}

//自定义用户属性
-(void)setUsrInfoWithkey:(NSString*)key object:(id)object{

    if ([AVUser currentUser]) {
        AVUser* usr = [AVUser currentUser];
        [usr setObject:object forKey:key];
        [usr saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

            [[AVUser currentUser] setObject:object forKey:key];
            [[AVUser currentUser] saveInBackground];
            NSLog(@"修改成功");
        }];
    }
}
//textView的代理方法
-(void)textViewDidEndEditing:(UITextView *)textView{
    NSLog(@"结束了简介的编辑");
    [self setUsrInfoWithkey:UINTRODUCEKEY object:textView.text];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
